//
//  CCAcitivityModel.m
//  Activity
//
//  Created by its on 15/5/14.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCAcitivityModel.h"
#import <AVOSCloud/AVOSCloud.h>
#import <LinqToObjectiveC/NSArray+LinqExtensions.h>

@implementation CCAcitivityModel

- (RACSignal *) getActivity:(NSString *)city {
  NSString *aql = [NSString stringWithFormat:@"select include author,* from activity where city = ? limit 1 order by -index"];
  NSArray *pvalue = @[city];
  return [self queryActivity:aql pvalues:pvalue];
}

- (RACSignal *) getHeader:(NSNumber *)order city:(NSString *)city {
  NSString *aql = [NSString stringWithFormat:@"select include author,* from activity where index>? and city = ? order by -index"];
  NSArray *pvalues = @[order, city];
  return [self queryActivity:aql pvalues:pvalues];
}

- (RACSignal *) getFoot:(NSNumber *) order limit:(NSInteger) limit city:(NSString *)city {
  NSString *aql = [NSString stringWithFormat:@"select include author.username,include author.headImage, * from activity where index < ? and city = ? limit ? order by -index"];
    NSArray *pvalues = @[order,city, @(limit)];
  return [self queryActivity:aql pvalues:pvalues];
}

- (RACSignal *) queryActivity:(NSString *)query pvalues:(NSArray *)pvales {
  return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    [AVQuery doCloudQueryInBackgroundWithCQL:query pvalues:pvales callback:^(AVCloudQueryResult *result, NSError *error) {
      if (error) {
        [subscriber sendNext:ERROR(2001)];
      } else if (result.results.count == 0){
        [subscriber sendNext:ERROR(2004)];
      } else {
        NSArray *array = [result.results linq_select:^id(AVObject *item) {
          return [item dictionaryForObject];
        }];
        array = [self objectForResponse:array andKlass:[CCAcitivity class] error:NULL];
        [subscriber sendNext:array];
      }
      
    }];
    return [RACDisposable disposableWithBlock:^{
    }];
  }];
}

- (id)objectForResponse:(id)response andKlass:(Class)klass error:(NSError **)error {
  id object = [response isKindOfClass:[NSArray class]] ?
  [MTLJSONAdapter modelsOfClass:klass fromJSONArray:response error:error] :
  [MTLJSONAdapter modelOfClass:klass fromJSONDictionary:response error:error];
  
  return object;
}

@end

@implementation CCAcitivity

- (id) init {
  if (self = [super init]) {
  }
  return self;
}
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
  return @{
           @"time" : @"time",
           @"title" : @"title",
           @"address" : @"address",
           @"money" : @"money",
           @"people" : @"people",
           @"coverImage":@"images",
           @"author":@"author.username",
           @"headImage":@"author.headImage",
           @"index":@"index",
           @"authorId":@"author.objectId",
           @"objectid":@"objectId"
           };
}


@end
